<!-- 成员变更 -->
<template>
  <div class="change_user">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="150">
      <Row :gutter="16">
        <Col span="22">
          <FormItem label="变更人员：">
            <span>{{ RowUserData.userName ? RowUserData.userName : '-' }}</span>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col span="22">
          <FormItem label="变更项：" prop="projectType">
            <Select
              v-model="formValidate.projectType"
              placeholder="请选择"
              class="cityConfigArea_moudle_select">
              <Option
                v-for="item in name == 'oncase' ? onCaseChangeArr : leaveCaseChangeArr"
                :key="item.key"
                :value="item.key"
                @click.native="handleClickprojectType(item.key)">
                {{ item.value }}
              </Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <div v-if="formValidate.projectType == 1">
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="当前角色：">
              <span>
                {{
                  RowUserData.roleNames
                    ? RowUserData.roleNames.length > 0
                      ? RowUserData.roleNames.join(',')
                      : '-'
                    : '-'
                }}
              </span>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="变更后角色：" prop="roleIds">
              <Select
                v-model="formValidate.roleIds"
                multiple
                placeholder="请选择"
                class="cityConfigArea_moudle_select"
                label-in-value
                @on-change="roleChange">
                <Option
                  v-for="item in roleIdsAttrSort"
                  :key="item.roleId"
                  :value="item.roleId"
                  :label="item.roleName" />
              </Select>
            </FormItem>
            <Row :gutter="16" type="flex" justify="start">
              <Col span="24" class="tips">
                <Icon type="md-alert" class="tips_icon" />
                <span class="AssignCustomers_name">
                  编辑角色日期时，请保证角色生效日期与分摊比例生效日期保持一致
                </span>
              </Col>
            </Row>
            <FormItem label="生效日期：" prop="effectDate">
              <DatePicker
                type="date"
                @on-change="formValidate.effectDate = $event"
                format="yyyy-MM-dd"
                :options="tmpDateOptions"></DatePicker>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16" v-if="tipsShow">
          <Col span="18" class="tips">
            <Icon type="md-alert" class="tips_icon" />
            {{ RowUserData.userName }}是任务责任人，角色变更后需重新设置责任人
            <span class="AssignCustomers_name" @click="totaskOwner">手动调整</span>
          </Col>
        </Row>
      </div>
      <div v-if="formValidate.projectType == 2">
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="当前进场日期：">
              <Select
                v-model="formValidate.currentDate"
                placeholder="请选择"
                class="cityConfigArea_moudle_select">
                <Option
                  v-for="(item, index) in currentDateAll"
                  :key="index"
                  :value="item"
                  @click.native="changeCurrentDate(item)">
                  {{ item }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="变更后进场日期：" prop="executeDate">
              <DatePicker
                type="date"
                @on-change="formValidate.executeDate = $event"
                format="yyyy-MM-dd"
                :options="currentOptions"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </div>
      <div v-if="formValidate.projectType == 3">
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="当前手机号：">
              <span>{{ RowUserData.phone ? RowUserData.phone : '-' }}</span>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="变更后手机号：" prop="phone">
              <Input type="text" v-model="formValidate.phone" maxlength="11"></Input>
            </FormItem>
          </Col>
        </Row>
      </div>

      <div v-if="formValidate.projectType == 4">
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="当前调出日期：">
              <Select
                v-model="formValidate.currentDate"
                placeholder="请选择"
                class="cityConfigArea_moudle_select">
                <Option
                  v-for="(item, index) in currentDateAll"
                  :key="index"
                  :value="item"
                  @click.native="changeCurrentDate(item)">
                  {{ item }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="变更后调出日期：" prop="executeDate">
              <DatePicker
                type="date"
                @on-change="formValidate.executeDate = $event"
                format="yyyy-MM-dd"
                :options="currentOptions"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </div>

      <div v-if="formValidate.projectType == 5">
        <Row :gutter="16">
          <Col span="18" class="tips">
            <Icon type="md-alert" class="tips_icon" />
            调入编制操作后该人员的编制将移入本案场
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="当前编制所属：">
              <span>{{ currentCaseInfo.dtCompile ? currentCaseInfo.dtCompile : '-' }}</span>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="异动日期：" prop="JYeffectDate">
              <DatePicker
                type="date"
                @on-change="formValidate.JYeffectDate = $event"
                format="yyyy-MM-dd"
                :options="currentCaseOptions"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </div>
    </Form>
    <div class="flex flex-horizontal-end btn-operate">
      <Button @click="handleClose">取消</Button>
      <Button type="primary" @click="submitFun()" style="margin-left: 8px">确定</Button>
    </div>
  </div>
</template>

<script>
  const validatePhone = (rule, value, callback) => {
    if (!value || !/^1[3456789]\d{9}$/.test(value)) callback(new Error('请输入正确的手机号'))
    else callback()
  }
  import teamsApi from '@/biz/buildingManagement/teams'
  import moment from 'moment'
  export default {
    props: {
      RowUserData: {
        type: Object,
        default: () => {
          return {}
        }
      },
      name: {
        type: String,
        default: 'oncase'
      }
    },
    data() {
      return {
        onCaseChangeArr: [
          { key: '1', value: '变更角色' },
          { key: '2', value: '变更进场日期' },
          { key: '3', value: '变更手机号码' }
        ],
        leaveCaseChangeArr: [
          { key: '2', value: '变更进场日期' },
          { key: '4', value: '变更调出日期' }
        ],
        roleIdsAttrSort: [],
        formValidate: {
          projectType: '',
          roleIds: [],
          phone: '',
          executeDate: null,
          effectDate: null,
          JYeffectDate: null
        },
        ruleValidate: {
          projectType: [
            {
              required: true,
              message: '请选择变更项',
              trigger: 'change'
            }
          ],
          roleIds: [
            {
              required: true,
              type: 'array',
              message: '请选择成员角色',
              trigger: 'change'
            }
          ],
          phone: [{ required: true, validator: validatePhone, trigger: 'change' }],
          executeDate: [
            {
              required: true,
              message: '请选择日期',
              trigger: 'blur'
            }
          ],
          effectDate: [
            {
              required: true,
              message: '请选择生效日期',
              trigger: 'change'
            }
          ],
          JYeffectDate: [
            {
              required: true,
              message: '请选择异动日期',
              trigger: 'change'
            }
          ]
        },
        tipsShow: false,
        taskArr: ['专案', '女专', '主委'],
        tmpDateOptions: {},
        currentDateAll: [],
        currentOptions: {},
        currentCaseOptions: {},
        currentCaseInfo: {
          //调入编制 当前编制所在案场信息
          dtCompile: '',
          buildingId: ''
        }
      }
    },
    methods: {
      //更改变更角色判断是否是任务责任人角色
      roleChange(val) {
        console.log(val, '123123')
        let changeRoles = []
        if (val && val.length > 0) {
          val.forEach((item) => {
            changeRoles.push(item.value)
          })
          this.getCurrentIsTaskUser(changeRoles)
        }
      },
      //获取所有前台角色和参与分摊比例的后台角色
      getFrontRoleinit() {
        teamsApi.getFrontRoles({ rewardShareFlag: 3 }).then((res) => {
          this.roleIdsAttrSort = res
        })
      },
      //获取成员编制所属
      getMemberCompile() {
        teamsApi.getMemberCompile({ userId: this.RowUserData.userId }).then((res) => {
          this.currentCaseInfo = { ...res }
        })
      },
      //获取最近的一条异动记录
      getUserChangeTimeLimit1() {
        teamsApi.getUserChangeTimeLimit1({ userId: this.RowUserData.userId }).then((res) => {
          if (res) {
            if (res.split(' ')[0] == this.$tool.dateFtt('yyyy-MM-dd', new Date())) {
              this.tipsFlag = true
            }
            this.currentCaseOptions = {
              disabledDate(date) {
                return (
                  date &&
                  (date.valueOf() < Date.parse(res.split(' ')[0]) + 43200000 || date.valueOf() > new Date())
                )
              }
            }
          }
        })
      },
      handleClose() {
        this.$emit('onClose')
      },
      submitFun() {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            let params = {
                operatorId: this.$dt.userInfo().userId,
                teamId: this.RowUserData.teamId,
                userId: this.RowUserData.userId,
                buildingId: this.$dt.buildInfo().housesId,
                operationType: this.formValidate.projectType
              },
              type = this.formValidate.projectType
            if (type == 1) {
              params.roleIds = this.formValidate.roleIds
              params.executeDate = this.formValidate.effectDate
              //当前人是任务责任人并且变更的角色没有专案、女专、主委 不允许提交
              // if (this.tipsShow && this.roletipsShow) {
              //   return false
              // }
            } else if (type == 2) {
              params.executeDate = this.formValidate.executeDate
              params.nowDate = this.formValidate.currentDate
            } else if (type == 3) {
              params.phone = this.formValidate.phone
            } else if (type == 4) {
              params.nowDate = this.formValidate.currentDate
              params.existDate = this.formValidate.executeDate
            } else if (type == 5) {
              params.executeDate = this.formValidate.JYeffectDate
              params.compileBuildingId = this.currentCaseInfo.buildingId
              params.caseCompile = true
            }
            teamsApi.editMember(params).then((res) => {
              if (type == 1) {
                this.$Message.success('角色变更成功!')
                if (res) {
                  this.unlocking('0102030200') && this.$emit('addUserRatio', res)
                }
              } else if (type == 2) {
                params.executeDate = this.formValidate.executeDate
                this.$Message.success('进场日期变更成功!')
              } else if (type == 3) {
                params.phone = this.formValidate.phone
                this.$Message.success('手机号变更成功!')
              } else if (type == 4) {
                params.executeDate = this.formValidate.executeDate
                this.$Message.success('调出日期变更成功!')
              }
              this.$emit('onClose')
              this.$emit('onChangeTable')
            })
          }
        })
      },
      handleClickprojectType(key) {
        // this.$refs.formValidate.resetFields()
        this.formValidate = {
          projectType: '',
          roleIds: [],
          phone: '',
          executeDate: null,
          effectDate: null,
          JYeffectDate: null
        }
        this.formValidate.projectType = key
        if (key == 2 || key == 4) {
          let type = key == 2 ? 1 : 2
          this.getFactoryDate(type)
        }
      },
      onChangeTaskUser(val) {
        this.getCurrentIsTaskUser()
      },
      totaskOwner() {
        this.$emit('openTask')
        this.$$on('changeTaskUser')
      },
      //当前成员是任务责任人
      getCurrentIsTaskUser(roleIds) {
        let params = {
          userId: this.RowUserData.userId,
          buildingId: this.$dt.buildInfo().housesId,
          roleIds
        }
        teamsApi.isTaskUser(params).then((res) => {
          this.tipsShow = res
        })
      },
      //获取用户所有进场/离场日期
      getFactoryDate(type) {
        let params = {
          userId: this.RowUserData.userId,
          buildingId: this.$dt.buildInfo().housesId,
          changeType: type
        }
        teamsApi.getFactoryDate({ ...params }).then((res) => {
          this.formValidate.currentDate = res[res.length - 1]
          this.currentDateAll = res
          this.curDisabled(this.formValidate.currentDate)
        })
      },
      changeCurrentDate(data) {
        this.curDisabled(data)
      },
      curDisabled(data) {
        let that = this
        let dataIndex = this.currentDateAll.indexOf(data)
        if (dataIndex == 0) {
          //首条记录不得晚于下一条记录 且不得晚于今天
          this.startDate = ''
          if (this.currentDateAll.length == 1) {
            this.endDate = moment(Date.now() + 86400000).format('YYYY-MM-DD')
          } else {
            this.endDate = this.currentDateAll[dataIndex + 1]
          }
        } else if (dataIndex == this.currentDateAll.length - 1) {
          //最后一条记录不得晚于今日 且不能早于上一条记录
          this.startDate = this.currentDateAll[dataIndex - 1]
          this.endDate = moment(Date.now() + 86400000).format('YYYY-MM-DD')
        } else {
          //可选生效日期必须大于等于上一条数据的生效日期且小于下一条数据的生效日期
          this.startDate = this.currentDateAll[dataIndex - 1]
          this.endDate = this.currentDateAll[dataIndex + 1]
        }
        this.currentOptions = {
          disabledDate(date) {
            return (
              date &&
              (date.valueOf() < Date.parse(that.startDate) - 86400000 ||
                date.valueOf() > Date.parse(that.endDate) - 86400000)
            )
          }
        }
      }
    },
    mounted() {
      if (this.RowUserData.compile != 1 && this.RowUserData.jyCompile) {
        this.onCaseChangeArr.push({ key: '5', value: '调入编制' })
        this.getMemberCompile()
        this.getUserChangeTimeLimit1()
      }
      let that = this
      this.getFrontRoleinit()
      this.tmpDateOptions = {
        disabledDate(date) {
          return (
            date && (date.valueOf() < Date.parse(that.RowUserData.factoryDate) || date.valueOf() > Date.now())
          )
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .tips {
    text-align: center;
    margin: 0 auto;
    margin-bottom: 15px;
    background-color: rgba(254, 252, 236, 1);
    width: auto;

    line-height: 32px;

    .tips_icon {
      font-size: 20px;
      color: #0f42a7;
    }

    .AssignCustomers_name {
      margin-left: 10px;
      cursor: pointer;
      color: #0f42a7;
    }
  }
</style>
